package com.smedi.ismedi.authority.starter.config;

import com.smedi.ismedi.authority.starter.handler.AuthorityHandler;
import com.smedi.ismedi.authority.starter.property.AuthorityInterceptorApiProperty;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.ArrayList;
import java.util.List;

@Slf4j
@Configuration
@RequiredArgsConstructor
public class AuthorityInterceptorConfig implements WebMvcConfigurer {
    private final AuthorityInterceptorApiProperty authorityInterceptorApiProperty;

    @Bean
    public AuthorityHandler AuthorityInterceptor() {
        return new AuthorityHandler();
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        List<String> adds = new ArrayList<>();
        List<String> excludes = new ArrayList<>();
        boolean used = false;

        // 配置拦截器
        if (authorityInterceptorApiProperty.getAdd() != null || authorityInterceptorApiProperty.getExclude() != null) {
            InterceptorRegistration config = registry.addInterceptor(AuthorityInterceptor());
            // 添加路由
            if (authorityInterceptorApiProperty.getAdd() != null) {
                for (String router : authorityInterceptorApiProperty.getAdd()) {
                    config.addPathPatterns(router);
                    adds.add(router);
                }
            }
            // 排除路由
            if (authorityInterceptorApiProperty.getExclude() != null) {
                for (String router : authorityInterceptorApiProperty.getExclude()) {
                    config.excludePathPatterns(router);
                    excludes.add(router);
                }
            }
            used = true;
        }

        // 打印日志
        if (authorityInterceptorApiProperty.isPrintLog()) {
            if (used) {
                log.info("启用身份验证拦截");
                for (String router : adds) {
                    log.info("+ 路由：{}", router);
                }
                for (String router : excludes) {
                    log.info("- 路由：{}", router);
                }
            } else {
                log.info("未启用身份验证拦截");
            }
        }
    }
}
